package com.alex.wechat.mp.handler;

import java.util.Date;
import java.util.Map;

import org.jeecgframework.web.cgform.common.CgAutoListConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.alex.wechat.core.handler.WxHandler;
import com.alex.wechat.mp.config.WxConsts;
import com.alex.wechat.mp.config.WxContext;
import com.alex.wechat.mp.fans.entity.WxFansEntity;
import com.alex.wechat.mp.fans.service.FansConverter;
import com.alex.wechat.mp.fans.service.WxFansServiceI;
import com.alex.wechat.mp.welcome.entity.WxWelcomeEntity;
import com.alex.wechat.mp.welcome.service.WxWelcomeServiceI;

import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.message.bean.WxXmlMessage;
import me.chanjar.weixin.message.rule.WxMessageHandler;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

/**
 * 用户关注公众号Handler
 * 
 * @author Debenson
 * @since 0.1
 */
@WxHandler(value = WxConsts.EVT_SUBSCRIBE)
public class SubscribeHandler implements WxMessageHandler {
  private static final Logger logger = LoggerFactory.getLogger(MassSendFinishHandler.class);

  @Autowired
  private WxFansServiceI fansServiceI;
  @Autowired
  private WxMpService wxMpService;
  @Autowired
  private WxWelcomeServiceI welcomeService;
  @Autowired
  private TemplateMsgReplyTool tplMsgReplyTool;

  @Override
  public String handle(WxXmlMessage wxMessage, Map<String, Object> context)
      throws WxErrorException {
    // 保存粉丝
    saveFans(wxMessage);

    WxMpXmlOutMessage m = reply(wxMessage);
    return m == null ? null : m.toXml();
  }

  private WxMpXmlOutMessage reply(WxMpXmlMessage wxMessage) {
    WxMpXmlOutMessage m = null;
    WxWelcomeEntity welcome = welcomeService.getByAccountId(WxContext.getOriginalId());
    if (welcome == null) {
      // 取默认的欢迎语
      m = WxMpXmlOutMessage.TEXT().content("感谢您的关注！").fromUser(wxMessage.getToUser())
          .toUser(wxMessage.getFromUser()).build();

    } else if (WxConsts.XML_MSG_TEXT.equals(welcome.getMsgType())) {
      m = tplMsgReplyTool.replyTextMsg(wxMessage, welcome.getTemplateId());

    } else if (WxConsts.XML_MSG_NEWS.equals(welcome.getMsgType())) {
      m = tplMsgReplyTool.replyNewsMsg(wxMessage, welcome.getTemplateId());

    } else {
      throw new RuntimeException("不支持的消息类型:" + welcome.getMsgType());
    }

    return m;
  }

  /**
   * 保存粉丝。
   * 
   * @param wxMessage
   */
  private void saveFans(WxMpXmlMessage wxMessage) {
    WxFansEntity fans = fansServiceI.getByOpenId(wxMessage.getFromUser());
    if (fans == null) {
      // 这个接口只能关注后才能调用
      try {
        WxMpUser wxMpUser = wxMpService.getUserService().userInfo(wxMessage.getFromUser(),
            WxConsts.LANG_ZH_CN);
        if (wxMpUser != null) {
          fans = FansConverter.getInstance().convert(wxMpUser);
          fans.setAccountId(wxMessage.getToUser());
          fans.setCreateDate(new Date());
        }
      } catch (WxErrorException e) {
        logger.error("获取粉丝信息失败", e);
      }
    }

    if (fans != null) {
      fans.setSubscribe(CgAutoListConstant.BOOL_TRUE);
      fans.setSubscribeTime(new Date().getTime());
      try {
        fansServiceI.saveOrUpdate(fans);
      } catch (Exception e) {
        logger.error("保存粉丝失败", e);
      }
    }
  }

};
